package com.hw.blog.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hw.blog.service.PmgrMenuService;
import com.hw.blog.utils.EgovMap;
import com.hw.blog.utils.SMCommonUtil;


/**
 * 메뉴관리
 * @author oracle
 *
 */
@Controller
public class PmgrMenuController extends BaseController{
	@Autowired
	private PmgrMenuService service;

	private Logger log = Logger.getLogger(getClass());
	
	//메뉴html 관리하는 paht
	private final String MENU_CONTEXT_PATH = "/WEB-INF/common/menu/";
	//menu Tree html 파일
	private final String MENU_CONTEXT_FILE_NAME = "MENU.html";
	//top 메뉴에 붙는 contents list 파일
	private final String ADMIN_MENU_FILE_NAME = "ADMIN_MENU.html";

	//CONTENT 저장 path
	private final String CONTENT_PATH = "/htmlContents";

	private final String IMAGE_PATH ="/uploadImg";
	/**
	 * 메뉴 목록 조회
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/menuList", method = RequestMethod.GET)
	public ModelAndView menuList(HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView("/pmgr/menu/menuList");
//		System.out.println("222");
		File backDir = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+MENU_CONTEXT_FILE_NAME ));
		if(backDir.exists()){
			FileReader fr = new FileReader(backDir);
			int data = 0;
			StringBuffer sb = new StringBuffer();
			while ((data = fr.read()) != -1) {
				char c = (char) data;
				sb.append(c);
			}
			fr.close();

			mav.addObject("menuList",sb.toString());	
		}
		
		mav.addObject("js","<script src='/common/js/jquery.nestable.min.js'></script><script src='/common/js/pmgr/menuList.js'></script>");
		
		

		return mav;
	}
	
	/**
	 * 관리자 상위 html  불러오기
	 * @param req
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/getTopContents", method = RequestMethod.GET)
	public void getTopContents(HttpServletRequest req, HttpServletResponse res) throws Exception {
//		ModelAndView mav = new ModelAndView();

		File backDir = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+ADMIN_MENU_FILE_NAME ));
		if(backDir.exists()){
			FileReader fr = new FileReader(backDir);
			int data = 0;
			StringBuffer sb = new StringBuffer();
			while ((data = fr.read()) != -1) {
				char c = (char) data;
				sb.append(c);
			}
			fr.close();

//			res.getOutputStream()
			res.getOutputStream().write(sb.toString().getBytes());
			res.getOutputStream().flush();
//			mav.addObject("menuList",sb.toString());	
		}

//		return mav;
	}
	
	/**
	 * 메뉴 저장
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/saveMenu", method = RequestMethod.POST)
	@Transactional(propagation=Propagation.REQUIRED)
	public ModelAndView saveMenu(@RequestParam Map<String,Object> param, HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView("redirect:./menuList.do?reload=Y");

		String menuList = param.get("menuList").toString().trim();
		
		//tree 파일저장
		File menuDir = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH));
		if(!menuDir.exists()){
			menuDir.mkdirs();
		}
		File menuFile = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+MENU_CONTEXT_FILE_NAME));

		//기존 메뉴 백업
		if(menuFile.exists()){
			SimpleDateFormat fmtDateTime = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
			Calendar dirDt = Calendar.getInstance();// 오늘
			File backDir = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+fmt.format(dirDt.getTime().getTime()) ));
			File backFile = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+fmt.format(dirDt.getTime().getTime())+"/MENU_"+fmtDateTime.format(dirDt.getTime().getTime())+".html" ));
			if(!backDir.exists()){
				backDir.mkdir();	
			}
			FileUtils.copyFile(menuFile, backFile);
		}
		
		
		FileWriter fw = new FileWriter(menuFile);
		BufferedWriter bw = new BufferedWriter(fw, 1024);
		bw.write(menuList);
		bw.close();
		fw.close();
		//파일 저장 끝
		
		//디비 저장
		
		String[] menu_seqs = 		param.get("menu_seqs").toString().split(";");
		String[] menu_nms = 		param.get("menu_nms").toString().split(";");
		String[] menu_depths = 	param.get("menu_depths").toString().split(";");
		String[] menu_urls = 		param.get("menu_urls").toString().split(";");
		String[] menu_types = 		param.get("menu_types").toString().split(";");
		String[] view_stats =		param.get("view_stats").toString().split(";");
		String[] user_writes = 		param.get("user_writes").toString().split(";");
		String[] use_yns = 			param.get("use_yns").toString().split(";");
		
		SimpleDateFormat fmtDateTime1 = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar dirDt1 = Calendar.getInstance();// 오늘

		Map map = new HashMap();
		map.put("reg_dt", fmtDateTime1.format(dirDt1.getTime().getTime())  	);
		service.backupMenu(map);
		service.deleteMenu();
		
		for(int i = 0; i < menu_seqs.length;i++){
			
			map.put("menu_seqs", menu_seqs[i].trim() );
			map.put("menu_nms", menu_nms[i].trim()   );
			map.put("menu_depths", menu_depths[i].trim() );
			map.put("menu_urls", menu_urls[i].trim()  );
			map.put("menu_types", menu_types[i].trim()  );
			map.put("view_stats", view_stats[i].trim()  );
			map.put("user_writes", user_writes[i].trim() );
			map.put("use_yns", use_yns[i].trim()   	);
			map.put("menu_ord", i   	);
		
			service.insertMenu(map);
			
		}
		//디비 저장 끝

		//관리자 메뉴 html 생성
		StringBuffer sbHtml = new StringBuffer();
		for(int i = 0; i < menu_seqs.length;i++){
			sbHtml.append("<li>");
//			int depth = Integer.parseInt( menu_depths[i].trim())-1;
//			for(int j=0 ;j < depth;j++){
//				sbHtml.append(" ");
//			}
			
			sbHtml.append("<a href=\"");
//			
			
			if("99".equals(menu_types[i].trim()) ){
				//html
				sbHtml.append("/pmgr/menu/boardHtml.do?menu_seq=");
				sbHtml.append(menu_seqs[i].trim());
			}else if("1".equals(menu_types[i].trim()) ){
				//일반게시판
				sbHtml.append("/pmgr/brd/brdList.do?menu_seq=");
				sbHtml.append(menu_seqs[i].trim());
			}else if("2".equals(menu_types[i].trim()) ){
				//FAQ
				sbHtml.append("/pmgr/faq/faqList.do?menu_seq=");
				sbHtml.append(menu_seqs[i].trim());
			}else if("3".equals(menu_types[i].trim()) ){
				//QnA
			}else if("4".equals(menu_types[i].trim()) ){
				//포토갤러리
			}else if("20".equals(menu_types[i].trim()) ){
				//메뉴 url링크
			}else{
				sbHtml.append("#");
			}
			
			sbHtml.append("\">");
			sbHtml.append(menu_nms[i].trim());
			sbHtml.append("</a>");
			sbHtml.append("</li>");
		}
		

		//tree 파일저장
		File adminMenuFile = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+ADMIN_MENU_FILE_NAME));

		//기존 메뉴 백업
		if(adminMenuFile.exists()){
			SimpleDateFormat fmtDateTime = new SimpleDateFormat("yyyyMMddHHmmss");
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
			Calendar dirDt = Calendar.getInstance();// 오늘
			File backFile = new File(req.getSession().getServletContext().getRealPath(MENU_CONTEXT_PATH+fmt.format(dirDt.getTime().getTime())+"/ADMIN_MENU_"+fmtDateTime.format(dirDt.getTime().getTime())+".html" ));
			FileUtils.copyFile(adminMenuFile, backFile);
		}
//		ADMIN_MENU_FILE_NAME
		
		FileWriter fw1 = new FileWriter(adminMenuFile);
		BufferedWriter bw1 = new BufferedWriter(fw1, 1024);
		bw1.write(sbHtml.toString());
		bw1.close();
		fw1.close();
		
		//메뉴 html 생성 끝
		
		return mav;
	}
	
	/**
	 * 메뉴 고유번호 조회
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@ResponseBody
	@RequestMapping(value="/pmgr/menu/getMenuSeq", method = RequestMethod.GET)
	public String getMenuSeq(ModelMap model) throws Exception {

		JSONObject json = new JSONObject();
	    json.put("menuSeq", service.getMenuSeq());

		return json.toString();
	}
	
	/**
	 * tinymce 파일 업로드 
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/uploadImage", method = RequestMethod.POST)
	public String uploadImage(ModelMap model,MultipartHttpServletRequest mRqst, HttpServletResponse res) throws Exception {
		
		MultiValueMap mulitFileMap =  mRqst.getMultiFileMap();
//		IMAGE_PATH
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
		Calendar dirDt = Calendar.getInstance();// 오늘

		String imgPath = IMAGE_PATH+"/"+fmt.format(dirDt.getTime().getTime());
		
		SMCommonUtil util = new SMCommonUtil();
		//첨부파일전송
		String[] files = {"upload"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),imgPath,false, files);

		Map returnMap = new HashMap();
		if("Y".equals((String)fileMap.get("error_yn"))){
//			String returnImg = "<script type=\"text/javascript\">alert('type error');</script>";
			returnMap.put("returnCd", "N");
			returnMap.put("error_msg", fileMap.get("error_msg"));
		}else{
//			String returnImg = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(38, '"+fileMap.get("upload")+"', '');</script>";
//			String returnImg = "<script type=\"text/javascript\">window.parent._setImg('"+fileMap.get("upload")+"')</script>";
			returnMap.put("returnCd", "Y");
			returnMap.put("filePaths", fileMap.get("upload_arr"));
		}
		
		model.addAttribute("data", returnMap);
		
		return "jsonView";
	}
	
	/**
	 * 파일업로드 
	 * @param model
	 * @param mRqst
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/uploadFiles", method = RequestMethod.POST)
	public String uploadFiles(ModelMap model,MultipartHttpServletRequest mRqst, HttpServletResponse res) throws Exception {
		
		MultiValueMap mulitFileMap =  mRqst.getMultiFileMap();
//		IMAGE_PATH
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
		Calendar dirDt = Calendar.getInstance();// 오늘

		String imgPath = IMAGE_PATH+"/"+fmt.format(dirDt.getTime().getTime());
		
		SMCommonUtil util = new SMCommonUtil();
		//첨부파일전송
		String[] files = {"upload"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),imgPath,true, files);

		Map returnMap = new HashMap();
		if("Y".equals((String)fileMap.get("error_yn"))){
//			String returnImg = "<script type=\"text/javascript\">alert('type error');</script>";
			returnMap.put("returnCd", "N");
			returnMap.put("error_msg", fileMap.get("error_msg"));
		}else{
//			String returnImg = "<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction(38, '"+fileMap.get("upload")+"', '');</script>";
//			String returnImg = "<script type=\"text/javascript\">window.parent._setImg('"+fileMap.get("upload")+"')</script>";
			returnMap.put("returnCd", "Y");
			returnMap.put("filePaths", fileMap.get("upload_arr"));
		}
		
		model.addAttribute("data", returnMap);
		
		return "jsonView";
	}
	
	
	@RequestMapping(value="/pmgr/menu/jsonWelcome", method = RequestMethod.GET)
	public String jsonWelcome(ModelMap model) {
//		ModelAndView mav = new ModelAndView("jsonView");
//		mav.addObject("message", "Hello world!");
//		return mav;
		List list = new ArrayList();
		
		EgovMap map = new EgovMap();
		
		map.put("abc_ddd", "dd");
		map.put("ddd_ddf", "dd");
		map.put("DdkdDfsdf", "dd");
		map.put("DdkdDfsdf", "dd");
		list.add(map);
		
	    model.addAttribute("message", "Hello world!");
	    model.addAttribute("list", list);
	    return "jsonView";
	}
	
	/**
	 * html  게시판 설정
	 * @param mRqst
	 * @param res
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/boardHtml")
	public ModelAndView boardHtml(@RequestParam Map<String,Object> param, HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView();
	    
		File backDir = new File(req.getSession().getServletContext().getRealPath(CONTENT_PATH+"/content_"+param.get("menu_seq")+".html" ));
		if(backDir.exists()){
			FileReader fr = new FileReader(backDir);
			int data = 0;
			StringBuffer sb = new StringBuffer();
			while ((data = fr.read()) != -1) {
				char c = (char) data;
				sb.append(c);
			}
			fr.close();

			mav.addObject("content",sb.toString());	
		}

		
		return mav;
	}
	
	/**
	 * html 파일 생성
	 * @param param
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/updateBoardHtml")
	public ModelAndView updateBoardHtml(@RequestParam Map<String,Object> param, HttpServletRequest req, HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView("redirect:./boardHtml.do?menu_seq="+param.get("menu_seq"));
		if(param.get("menu_seq")==null || !"".equals(param.get("menu_seq")) ||param.get("editor")==null || !"".equals(param.get("editor")) ){
			File menuDir = new File(req.getSession().getServletContext().getRealPath(CONTENT_PATH));
			if(!menuDir.exists()){
				menuDir.mkdirs();
			}
			File menuFile = new File(req.getSession().getServletContext().getRealPath(CONTENT_PATH+"/content_"+param.get("menu_seq")+".html"));

			//기존 메뉴 백업

			FileWriter fw = new FileWriter(menuFile);
			BufferedWriter bw = new BufferedWriter(fw, 1024);
			bw.write(param.get("editor").toString());
			bw.close();
			fw.close();
			
		}else{
			//에러 처리
		}

		return mav;
	}
	
	/**
	 * 메뉴 db 생성
	 * @param param
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/pmgr/menu/createDb")
	public String createDb(@RequestParam Map<String,Object> param,ModelMap model, HttpServletRequest req, HttpServletResponse res) throws Exception {
//		ModelAndView mav = new ModelAndView("redirect:./menuList.do");
		if(param.get("menu_seq")!=null && !"".equals(param.get("menu_seq")) && param.get("brd_type")!=null && !"".equals(param.get("brd_type")) ){
			//기존 db가 있을경우 백업

			String table = "";
			if("1".equals(param.get("brd_type"))){
				table ="brd_data_"+param.get("menu_seq");
			}else if("2".equals(param.get("brd_type"))){
				table ="faq_"+param.get("menu_seq");
			}else if("3".equals(param.get("brd_type"))){
//				table ="brd_data_"+param.get("menu_seq");
			}else if("4".equals(param.get("brd_type"))){
//				table ="brd_data_"+param.get("menu_seq");
			}
			if(!"".equals(table)){
				param.put("table", table )	;
				String exists = service.existsTable(param);
				if(null != exists && !"".equals(exists)){
					//기존테이블 백업 및 삭제
					if("2".equals(param.get("brd_type"))){
//						faq
						table ="faq_"+param.get("menu_seq");
						SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmm");
						Calendar dt = Calendar.getInstance();// 오늘
						
						String newTable = table +"_"+fmt.format(dt.getTime().getTime());
						param.put("query", BACKUP_QRY.replace("$table$", table).replace("$table_back$", newTable));
						service.runStatement(param);
						
						param.put("query", DROP_QRY.replace("$table$", table));
						service.runStatement(param);
					}else if("1".equals(param.get("brd_type"))){
						//게시판
						SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmm");
						Calendar dt = Calendar.getInstance();// 오늘
						
						//댓글
						table ="brd_cmt_"+param.get("menu_seq");
						String newTable = table +"_"+fmt.format(dt.getTime().getTime());
						param.put("query", BACKUP_QRY.replace("$table$", table).replace("$table_back$", newTable));
						service.runStatement(param);
						
						param.put("query", DROP_QRY.replace("$table$", table));
						service.runStatement(param);
						
						//파일
						table ="brd_file_"+param.get("menu_seq");
						newTable = table +"_"+fmt.format(dt.getTime().getTime());
						param.put("query", BACKUP_QRY.replace("$table$", table).replace("$table_back$", newTable));
						service.runStatement(param);
						
						param.put("query", DROP_QRY.replace("$table$", table));
						service.runStatement(param);
						
						//게시판
						table ="brd_data_"+param.get("menu_seq");
						newTable = table +"_"+fmt.format(dt.getTime().getTime());
						param.put("query", BACKUP_QRY.replace("$table$", table).replace("$table_back$", newTable));
						service.runStatement(param);
						
						param.put("query", DROP_QRY.replace("$table$", table));
						service.runStatement(param);

					}else{
						
					}
					
				}
				//테이블 신규 생성
				if("2".equals(param.get("brd_type"))){
//					faq
					param.put("query", CREATE_FAQ_QRY.replace("$table$", table));
					service.runStatement(param);
					param.put("query", CREATE_FAQ_INDEX_QRY.replace("$table$", table));
					service.runStatement(param);
				}else if("1".equals(param.get("brd_type"))){
					//게시판
					table ="brd_data_"+param.get("menu_seq");
					
					param.put("query", CREATE_BRD_QRY.replace("$table$", table));
					service.runStatement(param);
					param.put("query", CREATE_BRD_IDX_QRY.replace("$table$", table));
					service.runStatement(param);

					//댓글
					String table2 ="brd_cmt_"+param.get("menu_seq");
					String relation ="rel_brd_cmt_"+param.get("menu_seq");
					param.put("query", CREATE_BRD_CMT_QRY.replace("$table$", table2));
					service.runStatement(param);
					param.put("query", CREATE_BRD_CMT_IDX_QRY.replace("$table$", table2));
					service.runStatement(param);
					param.put("query", CREATE_BRD_REL1_QRY.replace("$table1$", table2).replace("$table$", table).replace("$rel_nm$", relation));
					service.runStatement(param);

					

					//파일
					String table3 ="brd_file_"+param.get("menu_seq");
					relation ="rel_brd_file_"+param.get("menu_seq");
					param.put("query", CREATE_BRD_FILE_QRY.replace("$table$", table3));
					service.runStatement(param);
					param.put("query", CREATE_BRD_FILE_INDEX_QRY.replace("$table$", table3));
					service.runStatement(param);
					param.put("query", CREATE_BRD_REL1_QRY.replace("$table1$", table2).replace("$table$", table).replace("$rel_nm$", relation));
					service.runStatement(param);
					
//					String 
				}else{
					
				}
			}
//			param.put("table", )
			model.addAttribute("code", "Y" );
		}else{
			//에러 처리
			model.addAttribute("code", "N" );
		}
	    
	    return "jsonView";
	}
	private final String  DROP_QRY ="DROP TABLE $table$;";
	private final String  BACKUP_QRY ="CREATE TABLE $table_back$ AS SELECT * FROM $table$;";
	
	private final String  CREATE_FAQ_QRY ="CREATE TABLE $table$(	fq_seq               INTEGER NOT NULL,	title                VARCHAR(255) NULL,	content              TEXT NULL,	reg_dt               VARCHAR(14) NULL,	user_name            VARCHAR(100) NULL);";
	private final String  CREATE_FAQ_INDEX_QRY ="ALTER TABLE $table$ ADD PRIMARY KEY (fq_seq);";
	
	private final String  CREATE_BRD_QRY ="CREATE TABLE $table$(		bd_no                INTEGER NOT NULL,	bd_title             VARCHAR(255) NULL,	bd_hit               INTEGER NULL,	bd_content           TEXT NULL,	reg_dt               VARCHAR(14) NULL,	bd_email             VARCHAR(50) NULL,	bd_pwd               VARCHAR(50) NULL,	secret_yn            VARCHAR(1) NULL,	notice_yn            VARCHAR(1) NULL,	user_name            VARCHAR(100) NULL,	phone                VARCHAR(20) NULL);";
	private final String  CREATE_BRD_IDX_QRY ="ALTER TABLE $table$ ADD PRIMARY KEY (bd_no);";
	
	private final String  CREATE_BRD_CMT_QRY ="CREATE TABLE $table$(	bd_no                INTEGER NOT NULL,	bd_cmt_no            INTEGER NOT NULL,	bc_nm                VARCHAR(50) NULL,	bc_content           TEXT NULL,	reg_dt               VARCHAR(14) NULL,	bc_pwd               VARCHAR(10) NULL);";
	private final String  CREATE_BRD_CMT_IDX_QRY ="ALTER TABLE $table$ ADD PRIMARY KEY (bd_no,bd_cmt_no);";
	
	private final String  CREATE_BRD_FILE_QRY ="CREATE TABLE $table$ (	bd_no                INTEGER NOT NULL,	bdf_no               INTEGER NOT NULL,	p_file_nm            VARCHAR(100) NULL,	view_file_nm         VARCHAR(100) NULL,	file_sz              VARCHAR(20) NULL,reg_dt               VARCHAR(14) NULL);";
	private final String  CREATE_BRD_FILE_INDEX_QRY ="ALTER TABLE $table$ ADD PRIMARY KEY (bd_no,bdf_no);";

	private final String  CREATE_BRD_REL1_QRY ="ALTER TABLE $table1$ ADD FOREIGN KEY $rel_nm$ (bd_no) REFERENCES $table$ (bd_no);";
}
